"use client"

import { useState, useEffect } from "react"
import { PlaylistCategories } from "@/components/playlist/playlist-categories"
import { PlaylistGrid } from "@/components/playlist/playlist-grid"

export default function PlaylistsPage() {
  const [selectedCategory, setSelectedCategory] = useState<number | string | null>(null)
  const [recentlyUsed, setRecentlyUsed] = useState<{ id: number | string; name: string }[]>([])

  // 从本地存储加载最近使用的分类
  useEffect(() => {
    const storedRecentlyUsed = localStorage.getItem("recentlyUsedPlaylistCategories")
    if (storedRecentlyUsed) {
      try {
        setRecentlyUsed(JSON.parse(storedRecentlyUsed))
      } catch (e) {
        console.error("解析最近使用的分类失败:", e)
      }
    }
  }, [])

  // 处理分类变更
  const handleCategoryChange = (categoryId: number | string | null) => {
    setSelectedCategory(categoryId)

    // 如果选择了分类，更新最近使用的分类
    if (categoryId !== null) {
      // 需要获取分类名称，这里假设我们有一个映射或者从当前上下文中获取
      // 在实际应用中，您可能需要从分类列表中查找名称
      const categoryName =
          document.querySelector(`button[data-category-id="${categoryId}"]`)?.textContent || `分类${categoryId}`

      const newCategory = { id: categoryId, name: categoryName }
      const newRecentlyUsed = [newCategory, ...recentlyUsed.filter((c) => c.id !== categoryId)].slice(0, 3)

      setRecentlyUsed(newRecentlyUsed)
      localStorage.setItem("recentlyUsedPlaylistCategories", JSON.stringify(newRecentlyUsed))
    }
  }

  return (
      <div className="min-h-screen">
        <div className="container mx-auto px-4 py-8">
          <PlaylistCategories
              selectedCategory={selectedCategory}
              onCategoryChange={handleCategoryChange}
              recentlyUsed={recentlyUsed}
          />
          <PlaylistGrid selectedCategory={selectedCategory} />
        </div>
      </div>
  )
}

